<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="empPage" >
        <el-form-item>
          <el-input v-model="empPage.keyword" placeholder="员工"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getEmpPage">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="departmentAddFrom">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-button type="danger" @click="empDeleteList" :disabled="this.selectData.length===0">批量删除</el-button>
<!--    主体-->
    <el-table
        :data="getPage.rows"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="id"
          label="id"
          width="50">
      </el-table-column>
      <el-table-column
          prop="username"
          label="员工名"
          width="130">
      </el-table-column>
      <el-table-column
          prop="password"
          label="员工密码"
          width="180">
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="130">
      </el-table-column>
      <el-table-column
          prop="headImage"
          label="头像"
          width="160">
      </el-table-column>
      <el-table-column
          prop="age"
          label="年龄"
          width="100">
      </el-table-column>
      <el-table-column
          prop="departmentName"
          label="部门"
          width="200">
      </el-table-column>
      <el-table-column
          label="操作"
          width="195">
        <template slot-scope="scope">
          <el-button @click="departmentDelete(scope.row)" type="text" size="small">删除</el-button>
          <el-button @click="departmentFrom(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="setEmpRoleFrom(scope.row)" type="text" size="small">设置角色</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    分页-->
    <el-pagination style="float:right;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="empPage.pageIndex"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="getPage.total">
    </el-pagination>


<!--弹框-->
    <el-dialog title="添加/修改" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="empFrom" label-width="80px" :rules="addFormRules" ref="empFrom">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="empFrom.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="empFrom.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="empFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="empFrom.age" ></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader v-model="empFrom.department_id"
                       :options="deptTree"
                       :props="{
                           checkStrictly: true,
                           label:'name',
                           value:'id'
                       }"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="上传头像">
            <el-input v-model="empFrom.headImage"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="empSave" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--角色弹框-->
    <el-dialog title="添加/修改" :visible.sync="dialogFormVisibleRole" :close-on-click-modal="false">
      <div style="margin: 15px 0;"></div>
      <el-checkbox :indeterminate="isIndeterminateEmpRole" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="EmpRole.roleSns" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="role in AllRole" :label="role.sn" :key="role.sn">{{role.name}}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogFormVisibleRole = false">取消</el-button>
        <el-button type="primary" @click.native="EmpRoleSave">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {batchRemoveUser} from "../../api/api";

export default {
  name:"Department",
  data() {
    return {
      getPage:{
        total: 10,
        rows:[]
      },
      empPage:{
        pageSize:10,
        pageIndex:1,
        keyword:null
      },
      //多级部门
      deptTree:[],
      //获取选择的ids
      selectData:[],//列表选中列
    //  是否打开弹框
      dialogFormVisible:false,
    //  加载
      addLoading: false,
    //  添加或者修改页面数据
      empFrom:{
        id:null,
        username:"",
        password:"",
        email:"",
        headImage:"",
        age:null,
        department_id:null,
        departmentName:""
      },
    //输入规则
      addFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      uploadUrl: "http://localhost:8081/employee",
      fileList: null,

    //  获取所有角色
      AllRole:[],
      //角色弹框
      dialogFormVisibleRole:false,
      //保存角色
      EmpRole:{
        id:null,
        roleSns:[]
      },
    //  角色回显
      EmpRoleSns:[],
    //  是否选择状态
      isIndeterminateEmpRole: true,
    //
      checkAll:false
    }
  },
  methods:{

    //员工角色保存
    EmpRoleSave(){
      this.$confirm('此操作将修改角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(res =>{
          //  调用保存
            console.log("选择的sn")
            console.log(this.EmpRole.roleSns)
            this.$http.post("/employee/roles",this.EmpRole)
                .then(res =>{
                    res =res.data;
                    if (res.code == 200){
                      this.$message({
                        type: 'success',
                        message: res.msg
                      });
                    //  关闭弹窗
                      this.dialogFormVisibleRole = false;
                    //  重新查询
                      this.getEmpPage();
                    }
                }).catch(res =>{
              this.$message({
                type: 'error',
                message: "网络异常，请稍后在使"
              });
            })
          }).catch(res =>{
        this.$message({
          type: 'info',
          message: "已取消"
        });
      })
    },


    handleCheckAllChange(val){
      this.EmpRole.roleSns = val ? this.AllRole : [];
      this.isIndeterminateEmpRole = false;
    },

    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.EmpRole.roleSns.length;
      this.isIndeterminateEmpRole = checkedCount > 0 && checkedCount < this.EmpRole.roleSns.length;
    },


    //获取所有角色
    getAllRoles(){
      this.$http.get("/Role/all")
          .then(res =>{
            res = res.data;
            if (res.code == 200){
              //获取所有权限
              this.AllRole = res.data;
            }
          }).catch(res =>{
      })
    },

    //查询员工拥有角色sn
    getEmpRoleSn(id){
      this.$http.get("/employee/getRoles/"+id)
          .then(res => {
            res = res.data;
            if (res.code == 200){
              this.EmpRole.roleSns = res.data;
            }
          }).catch(res =>{

      })
    },


    //给员工设置角色弹框
    setEmpRoleFrom(row){
    //  获取所有角色
      this.getAllRoles();
      console.log("所有角色")
      console.log(this.AllRole)
    //  回显数据
      this.getEmpRoleSn(row.id);
      console.log("员工拥有角色")
      console.log(this.EmpRole.roleSns);
      this.EmpRole.id = row.id;
      //  角色弹框
      this.dialogFormVisibleRole = true;
    },

    //测试上传文件(注意web的上下文)
    handleBeforeUpload(file){
      this.uploadUrl = "http://localhost:8081/employee"
      console.log("开始上传，上传的文件为："+file)
      let formData = new FormData();
      formData.append("multipartFiles", file);
      this.$http.post("http://localhost:8081/employee",formData,{
        headers: {'Content-Type': 'multipart/form-data' }
      }).then((res) => {
        console.log("文件上传返回："+res)
      }).catch(error => {
        console.log("文件上传异常:"+error)
      })
    },
    //批量删除
    empDeleteList(){
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.addLoading = true;
        this.$http.patch("/employee",this.selectData)
          .then(res =>{
            res =res.data;
            if (res.code==200){
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.addLoading = false;
              this.getEmpPage();
            }else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          }).catch(res =>{
          this.$message({
            message: "网络异常",
            type: 'error'
          });
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        });
      });
    },
    //提交添加或者修改
    empSave(){
      let emp = this.empFrom;
      let ids =emp.department_id;
      if (ids !==null && ids !=="" && ids .length > 0){
        ids = ids[ids.length-1];
      }
      emp.department_id = ids;
      this.$http.post("/employee",emp)
          .then(res =>{
            if (res.data.code==200){
              this.dialogFormVisible = false;
              this.addLoading = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
            //  刷新页面
              this.getEmpPage();
            }
          })
          .catch(res =>{
            this.$message({
              type: 'error',
              message: "未知错误"
            });
          });
    },
    //  获取到多级部门
    getDepThreeLevel(){
      this.$http.get("/department/threeLevel")
          .then(res => {
            res = res.data;
            if (res.code == 200){
              this.deptTree = res.data;
            }
          }).catch(res => {
        this.$message({
          type: 'error',
          message: "未知错误"
        });
      });
    },
    //打开弹框添加部门
    departmentAddFrom(){
      this.dialogFormVisible = true;
      this.empFrom ={
        id:null,
        username:"",
        password:"",
        email:"",
        headImage:"",
        age:null,
        department_id:null,
        departmentName:""
      };
    //  获取到多级部门
        this.getDepThreeLevel();
    },
    //打开弹框修改部门
    departmentFrom(row){
      this.dialogFormVisible = true;
      //获取到多级部门
      this.getDepThreeLevel();
      this.empFrom = row;
    },
    //删除某行数据
    departmentDelete(row){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = row.id;
        this.$http.delete("/employee/"+id)
            .then(res =>{
              if (res.data.code==200){
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                this.getEmpPage()
              }else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
            .catch(res =>{
              this.$message({
                type: 'error',
                message: "网络异常，请稍后在使"
              });
            })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //多行选择
    handleSelectionChange(val){
      let ids = val.map(val => val.id);
      this.selectData = ids;
    },
    handleSizeChange(val){
      this.empPage.pageSize = val;
      this.empPage.pageIndex = 1;
      console.log(this.empPage);
      this.getEmpPage();
    },
    handleCurrentChange(val){
      console.log(val);
      this.empPage.pageIndex = val;
      this.getEmpPage();
    },
    getEmpPage(){
      console.log(this.empPage)
      this.$http.post("/employee/page",this.empPage)
        .then(result=>{
          result = result.data;
          console.log(result)
          this.getPage = result.data;
          console.log(this.getPage);
        })
        .catch(result=>{
          alert("失败");
        });
    }
  },
  mounted(){
    this.getEmpPage();
  }
}
</script>

<style scoped>
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand{
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
